var baseExtend = "../../script/";

layui.define(['laytpl', 'upload-mobile', 'layer-mobile', 'zepto'], function (exports) {
    layui.config({
        base: baseExtend
    }).use(['justchatSocketMgr', 'justchatApiMgr','storage'],function(){
        var v = '2.1.0';
        var $ = layui.zepto;
        var laytpl = layui.laytpl;
        var layer = layui['layer-mobile'];
        var upload = layui['upload-mobile'];
        var device = layui.device();
        var justchatSocketMgr = layui.justchatSocketMgr;
        var justchatApiMgr = layui.justchatApiMgr;

        // var justchatModel = layui.justchatModel;
        // var justchatFunc = layui.justchatFunc;
        // var justchatCustom = layui.justchatCustom;
        window.isAgency = window.location.search.includes('role=agent');
        var imid = getParam('imid');
        var storage = layui.storage(imid);
        var officialID = 88888; // 官方运营id

        // 当前正在聊天对象id
        window.currentTarget = null;

        window.socketState = 'pending';

        window.sendMessageTimers = {};


        var PAY_TYPE_NAME = {
            1: "支付宝充值",
            2: "微信充值",
            3: "花呗充值",
            4: "信用卡充值",
            5: "银行卡充值",
        };

        var PAY_TYPE_CLASS_NAME = {
            1: "justchat-bg-alipay",
            2: "justchat-bg-wechat",
            3: "justchat-bg-huabei",
            4: "justchat-bg-bank",
            5: "justchat-bg-bank",

        };

        var SHOW = 'layui-show', THIS = 'layim-this', MAX_ITEM = 100;

        //回调
        var call = {};

        // 将方法挂载到window上方便模版使用
        window.getMessageDate = getMessageDate;
        window.compatibleImgUrl = compatibleImgUrl;

        // 监听当前的socket的连接状态
        justchatSocketMgr.watchSocketState(function(currentSocketState){
            // var role = getParam('role');

            // 代理忽视。
            // if(role === 'agent') return

            socketState = currentSocketState

        });




        //对外API
        var LAYIM = function () {
            this.v = v;
            touch($('body'), '*[layim-event]', function (e) {
                var othis = $(this), methid = othis.attr('layim-event');
                events[methid] ? events[methid].call(this, othis, e) : '';
            });
        };

        //避免tochmove触发touchend
        var touch = function (obj, child, fn) {
            var move, type = typeof child === 'function', end = function (e) {
                var othis = $(this);
                if (othis.data('lock')) {
                    return;
                }
                move || fn.call(this, e);
                move = false;
                othis.data('lock', 'true');
                setTimeout(function () {
                    othis.removeAttr('data-lock');
                }, othis.data('locktime') || 0);
            };

            if (type) {
                fn = child;
            }

            obj = typeof obj === 'string' ? $(obj) : obj;

            if (!isTouch) {
                if (type) {
                    obj.on('click', end);
                } else {
                    obj.on('click', child, end);
                }
                return;
            }

            if (type) {
                obj.on('touchmove', function () {
                    move = true;
                }).on('touchend', end);
            } else {
                obj.on('touchmove', child, function () {
                    move = true;
                }).on('touchend', child, end);
            }
        };

        //是否支持Touch
        var isTouch = /Android|iPhone|SymbianOS|Windows Phone|iPad|iPod/.test(navigator.userAgent);

        //底部弹出
        layer.popBottom = function (options) {
            layer.close(layer.popBottom.index);
            layer.popBottom.index = layer.open($.extend({
                type: 1
                , content: options.content || ''
                , shade: false
                , className: 'layim-layer'
            }, options));
        };

        //基础配置
        LAYIM.prototype.config = function (options) {
            options = options || {};
            options = $.extend({
                title: '我的IM'
                , isgroup: 0
                , isNewFriend: !0
                , voice: 'default.mp3'
                , chatTitleColor: '#fff'
            }, options);
            init(options);
        };

        //监听事件
        LAYIM.prototype.on = function (events, callback) {
            if (typeof callback === 'function') {
                call[events] ? call[events].push(callback) : call[events] = [callback];
            }
            return this;
        };

        //打开一个自定义的会话界面
        LAYIM.prototype.chat = function (data) {
            if (!window.JSON || !window.JSON.parse) return;
            return popchat(data, -1), this;
        };

        //打开一个自定义面板
        LAYIM.prototype.panel = function (options) {
            return popPanel(options);
        };

        //获取所有缓存数据
        LAYIM.prototype.cache = function () {
            return cache;
        };

        //接受消息
        LAYIM.prototype.getMessage = function (data) {
            return getMessage(data), this;
        };


        //设置好友在线/离线状态
        LAYIM.prototype.setFriendStatus = function (id, type) {
            var list = $('.layim-friend' + id);
            list[type === 'online' ? 'removeClass' : 'addClass']('layim-list-gray');
        };

        //设置当前会话状态
        LAYIM.prototype.setChatStatus = function (str) {
            var thatChat = thisChat(), status = thatChat.elem.find('.layim-chat-status');
            return status.html(str), this;
        };

        //解析聊天内容
        LAYIM.prototype.content = function (content) {
            return layui.data.content(content);
        };

        LAYIM.prototype.convertStampToTime = function (timestamp) {
            return layui.data.date(timestamp);
        };

        LAYIM.prototype.addPicToChat = function (urls,cid) {
            sendPicToChat(urls,cid)
        };

        LAYIM.prototype.beforePicUpload = function (cid) {
            beforePicUpload(cid)
        };

        //渲染payTypes
        LAYIM.prototype.renderPayTypes = function (html) {
            $('.justchat-pay-types').show();
            // $('.layim-chat-main').removeClass("agencymain");
            // $('.layim-chat-main').addClass("just-chat-main-pay");
            var $main = $('.layim-chat-main');
            $main.removeClass("agencymain");
            $main.addClass("just-chat-main-pay");

            var main = $main.get(0);
            if(main){
                main.scrollTop = main.scrollHeight;
            }

            renderPayTypes(html);
        };

        //列表内容模板
        var listTpl = function (options) {
            var nodata = {
                friend: "该分组下暂无好友"
                , group: "暂无群组"
                , history: "当前无消息"
            };

            options = options || {};

            //如果是历史记录，则读取排序好的数据
            if (options.type === 'history') {
                options.item = options.item || 'd.sortHistory';
            }

            return ['{{# var length = 0;layui.each(' + options.item + ', function(i, data){ length++; }}'
                , '<li layim-event="chat" data-type="' + options.type + '" data-index="' + (options.index ? '{{' + options.index + '}}' : (options.type === 'history' ? '{{data.type}}' : options.type) + '{{data.id}}') + '" class="layim-history-item layim-' + (options.type === 'history' ? '{{data.type}}' : options.type) + '{{data.id}} {{ data.status === "offline" ? "layim-list-gray" : "" }}  {{"layim-chat-friend"+data.id}}"><div><img class="avatar" src="{{isAgency?agentDefultImg:playerDefultImg}}"></div><span class="name">{{ data.username||data.groupname||data.name||"佚名" }}</span><span class="justchat-multiple-time">{{ getMessageDate(data.time) || "" }}</span><p class="test">{{ data.remark||data.sign||"" }}</p><span class="layim-msg-status {{data.unMsgNum?"layui-show":""}}">{{data.unMsgNum}}</span><div data-targetid={{data.id}} class="delete-layim-chat-li">删除聊天</div></li>'
                , '{{# }); if(length === 0){ }}'
                , '<li class="layim-null">' + (nodata[options.type] || "当前无消息") + '</li>'
                , '{{# } }}'].join('');
        };

        //公共面板
        var comTpl = function (tpl, anim, back) {
            return ['<div class="layim-panel' + (anim ? ' layui-m-anim-left' : '') + '">'
                , '<div class="layim-title">'
                , '<p>'
                , (back ? '<i class="layui-icon layim-chat-back" layim-event="back">&#xe603;</i>' : '')
                , '{{ d.title || d.base.title }}<p style="color:#fff;text-align:center;font-size:18px;" class="layim-chat-status"><span class="chat-title">消息</span><span class="justchat-status"></span></p>'
                , '{{# if(d.data){ }}'
                , '{{# if(d.data.type === "group"){ }}'
                , '<i class="layui-icon layim-chat-detail" layim-event="detail">&#xe613;</i>'
                , '{{# } }}'
                , '{{# } }}'
                // , isAgency?'<select lay-verify="" name="platform" class="platform" lay-ignore><option value="">平台筛选</option><option value="010">黑金</option></select>':''
                , '</p>'
                , '<img src="../../img/clear_history.png" class="clearStorage" layim-event="clearStorage" />'
                , '</div>'
                , '<div class="layui-unselect layim-content">'
                , tpl
                , '</div>'
                , '</div>'].join('');
        };

        //聊天面板
        var chatTpl = function (tpl, anim, back) {
            return ['<div class="layim-panel' + (anim ? ' layui-m-anim-left' : '') + '">'
                , '<div class="layim-title" style="background:#fff;">'
                , '<div>'
                , (back ? '<i class="layui-icon layim-chat-back" style="color:#000" layim-event="back">&#xe603;</i>' : '')
                , '<div class="layim-chat-status" style="line-height: 40px;"><p style="color:#000" class="justchat-chat-title"><span class="chat-title">{{ d.title || d.base.title }}</span><span class="justchat-status"></span></div></p>'
                , '{{# if(d.data){ }}'
                , '{{# if(d.data.type === "group"){ }}'
                , '<i class="layui-icon layim-chat-detail" layim-event="detail">&#xe613;</i>'
                , '{{# } }}'
                , '{{# } }}'
                , '</div>'
                , (isAgency?'':'<span id="go-complaint" class="go-complaint"><i style="font-size:16px;margin-right:3px;" class="layui-icon-release layui-icon"></i>投诉</span>')
                , '</div>'
                , '<div class="layui-unselect layim-content">'
                , tpl
                , '</div>'
                , '</div>'].join('');
        };

        //主界面模版
        var elemTpl = ['<div class="layui-layim">'
            , '<div class="layim-tab-content layui-show">'
            // ,'<p class="connect-tip layui-hide"><i class="layui-icon layui-icon-tips icon"></i><span class="tip-font">未连接</span></p>'
            , '<ul class="layim-list-friend" id="layim-chat-friend">'
            , '<ul class="layui-layim-list layui-show layim-list-history">'
            , listTpl({
                type: 'history',
            })
            , '</ul>'
            , '</ul>'
            , '</div>'
            , '<div class="layim-tab-content">'
            , '<ul class="layim-list-top">'
            , '{{# if(d.base.isNewFriend){ }}'
            , '<li layim-event="newFriend"><i class="layui-icon">&#xe654;</i>新的朋友<i class="layim-new" id="LAY_layimNewFriend"></i></li>'
            , '{{# } if(d.base.isgroup){ }}'
            , '<li layim-event="group"><i class="layui-icon">&#xe613;</i>群聊<i class="layim-new" id="LAY_layimNewGroup"></i></li>'
            , '{{# } }}'
            , '</ul>'
            , '<ul class="layim-list-friend" >'
            , '{{# layui.each(d.friend, function(index, item){ var spread = d.local["spread"+index]; }}'
            , '<li>'
            , '<h5 layim-event="spread" lay-type="{{ spread }}"><i class="layui-icon">{{# if(spread === "true"){ }}&#xe61a;{{# } else {  }}&#xe602;{{# } }}</i><span>{{ item.groupname||"未命名分组"+index }}</span><em>(<cite class="layim-count"> {{ (item.list||[]).length }}</cite>)</em></h5>'
            , '<ul class="layui-layim-list {{# if(spread === "true"){ }}'
            , ' layui-show'
            , '{{# } }}">'
            , listTpl({
                type: "friend"
                , item: "item.list"
                , index: "index"
            })
            , '</ul>'
            , '</li>'
            , '{{# }); if(d.friend.length === 0){ }}'
            , '<li><ul class="layui-layim-list layui-show"><li class="layim-null">暂无联系人</li></ul>'
            , '{{# } }}'
            , '</ul>'
            , '</div>'
            , '<div class="layim-tab-content">'
            , '<ul class="layim-list-top">'
            , '{{# layui.each(d.base.moreList, function(index, item){ }}'
            , '<li layim-event="moreList" lay-filter="{{ item.alias }}">'
            , '<i class="layui-icon {{item.iconClass||\"\"}}">{{item.iconUnicode||""}}</i>{{item.title}}<i class="layim-new" id="LAY_layimNew{{ item.alias }}"></i>'
            , '</li>'
            , '{{# }); if(!d.base.copyright){ }}'
            , '<li layim-event="about"><i class="layui-icon">&#xe60b;</i>关于<i class="layim-new" id="LAY_layimNewAbout"></i></li>'
            , '{{# } }}'
            , '</ul>'
            , '</div>'
            , '</div>'].join('');

        //聊天主模板
        var elemChatTpl = ['<div class="layim-chat layim-chat-{{d.data.type}}">'
            , '<div class="layim-chat-main just-chat-main-pay agencymain">'
            , '<ul></ul>'
            , '</div>'
            , '<form action="javascript:return false;" class="layim-chat-footer" for="layimInput">'
            , isAgency?'<div class="justchat-pay-types types-agency"><div class="types-item"><ul class="quick-reply-btn-box"></ul><span style="color:#fff;background:#58a0eb"  class="show-quick-reply-btn layui-btn layui-btn-primary layui-btn-sm layui-btn-radius">快捷回复</span></div><div class="types-item"><span style="color:#fff;background:orange"  class="show-send-acount-btn layui-btn layui-btn-primary layui-btn-sm layui-btn-radius">发送账号</span><ul class="send-account-btn-box"></ul></div></div>':'<div class="justchat-pay-types" for="layimInput"></div>'
            // , '<div class="chat-footer-box">'
            , '<div class="layim-chat-send">'
            ,'<input type="serch" id="layimInput"  autocomplete="off" class="justchat-amount-input">'
            ,'<span class="layui-icon layim-tool-face" title="选择表情" layim-event="face">&#xe60c;</span>'
            ,'<span class="layui-icon layim-tool-toggle" title="展开" layim-event="toggleTools">&#xe608;</span>'
            ,'<button class="layim-send layui-disabled layui-hide"  layim-event="send">发送</button>'
            ,'</div>'
            ,'<div class="layim-chat-tool layui-hide" data-json="{{encodeURIComponent(JSON.stringify(d.data))}}">'
            /*, '{{# if(d.base && d.base.uploadImage){ }}'*/
            , '<span class="layui-icon layim-tool-image" title="上传图片">&#xe60d;<input id="justchat_uploadPic" type="file" name="file" multiple /></span>'
            /*, '{{# }; }}'*/
            , '{{# if(d.base && d.base.uploadFile){ }}'
            , '<span style="display:none;" class="layui-icon layim-tool-image" title="发送文件" layim-event="image" data-type="file">&#xe61d;<input type="file" name="file"></span>'
            , '{{# }; }}'
            , '{{# layui.each(d.base.tool, function(index, item){ }}'
            , '<span style="display:none;" class="layui-icon  {{item.iconClass||\"\"}} layim-tool-{{item.alias}}" title="{{item.title}}" layim-event="extend" lay-filter="{{ item.alias }}">{{item.iconUnicode||""}}</span>'
            , '{{# }); }}'
            , '</div>'
            // ,'</div>'
            , '</form>'
            , '</div>'].join('');


        // 兼容发送的图片地址
        function compatibleImgUrl(url) {
            var lastUrl = url;
            // 最老的情况
            if(/img\[(.+)\]/g.test(url)){
              lastUrl = /img\[(.+)\]/g.exec(url)[1]
            }
            // 本地图片
            else if(/local\[(.+)\]/g.test(url)){
              lastUrl = /local\[(.+)\]/g.exec(url)[1]
            }
            else{ 
              // lastUrl = /(http:\/\/|https:\/\/)/.test(url)? url : 'http://im.bolansuzhou.com/' + url  //test
              lastUrl = /(http:\/\/|https:\/\/)/.test(url)? url : 'http://im.beierche.net/' + url
            }
            return lastUrl
        }

        //补齐数位
        var digit = function (num) {
            return Number(num) < 10 ? '0' + (num | 0) : num;
        };

        // 获取聊天时间
        function getMessageDate(d) {
            if(!d) return ''
            var dArr = d.split(' ');
            if(isToday(dArr[0])) return dArr[1];
            if(isYesterday(dArr[0])) return '昨天 ' + dArr[1];
            return d;
        }

         // 判断是否是今天
         function isToday(str){
            var d = new Date();
            var y = d.getFullYear(); // 年
            var m = digit(d.getMonth() + 1); // 月份从0开始的
            var d = digit(d.getDate()); //日
            return str == (y + '-' + m + '-' + d);
        }

        // 判断是否是昨天
        function isYesterday(str){
            var d = new Date();
            var time = d.getTime();
            var before = time - 24*60*60*1000;
            var yesterday = new Date(before);
            var y = yesterday.getFullYear(); // 年
            var m = digit(yesterday.getMonth() + 1); // 月份从0开始的
            var d = digit(yesterday.getDate()); //日
            return str == (y + '-' + m + '-' + d)
        }

        // 添加超时监听
        function addSendMessageTimer(cid) {

            if(socketState === 'close') return

            var timeout = 60000; // 1分钟后超时
            var timeId = setTimeout(function(){
               var $chat = $("#chat-"+cid);
               $chat.find(".layim-chat-loading").remove();
               if($chat.hasClass("layim-chat-mine")){
                    $chat.prepend('<i class="layui-icon layui-icon-tips layim-chat-tips"></i>')
               }
            },timeout);
            window.sendMessageTimers[cid] = timeId;
        }

        // 关闭菜单
        function closeMenu(){
            $("#menu").hide();
            document.body.removeEventListener('click',closeMenu,false);
        }

        // 初始化代理删除单个聊天记录
        function initDeleteHistoryItem(){
            if(!isAgency) return

            window.oncontextmenu=function(e){
                e.preventDefault();
                var target = e.target;
                if(target.tagName === 'li'){
                    var $ele = target
                }else{
                    var $ele = $(target).closest('li')
                }

                if(!$ele.hasClass('layim-history-item')) return

                document.body.addEventListener('click',closeMenu,false);

                var x = e.clientX;
                var y = e.clientY;

                var $menu = $("#menu").on('click','.menu-delete-chat',function(){
                    $("#menu").off('click','.menu-delete-chat');
                    $menu.hide();
                    var targetName = $ele.find('.name').text();
                    popConfirm({
                        content:'确定删除与【'+targetName+'】的对话？',
                        ok:function(){
                            var targetId = $ele.attr('data-index').slice(6);

                            storage.deleteChatlog({
                                id:targetId
                            })
                            storage.deleteHistory({
                                id:targetId
                            })
                            $ele.remove();
                            var $ul = $(".layim-list-history");
                            var isEmpty = true
                            for(var key in storage.getAllHistory()){
                                isEmpty = false;
                                break;
                            }
                            if(isEmpty){
                                $ul.append('<li class="layim-null">当前无消息</li>')
                            }

                            var unMsgNum = countAllUnMsg();
                            initUI_justchat(unMsgNum);

                            window.parent.postMessage({unMsgtotal:unMsgNum},"*");
                        }
                    })
                })

                $menu.css({left:x,top:y}).show();
            }
        }

        // 初始化代理发送付款账户
        function initSendAccount(){
            $('.show-send-acount-btn').hide()
            if(!isAgency || (currentTarget == officialID)) return
            justchatApiMgr.agentGetPayTypes(currentTarget,function(res){
                if(res.status == 0){
                    var pays =  res.data.payTypes;
                    var btns = [];
                    pays.forEach(function(item,index){
                        btns.push({
                            title:PAY_TYPE_NAME[index+1],
                            payType:item
                        })
                    })
                    if(!(btns && btns.length>0)){
                        $('.show-send-acount-btn').hide()
                        return
                    }
                    $('.show-send-acount-btn').show()
                    var $box = $('.send-account-btn-box');
                    $('.show-send-acount-btn').show().on('click',function(event){
                        $(".quick-reply-btn-box").hide();
                        $box.css('display', $box.css('display')=='block'?'none':'block')
                        event.stopPropagation();
                        return false;
                   })

                   $box.empty();
                   var colors = ['#508ae7','#06e104','#58a0eb','#d3804b','#e1af4f'];
                   btns.forEach(function(item,index){
                        var $ele = $('<li style="color:'+colors[item.payType-1]+'" class="send-account-btn" data-paytype="'+item.payType+'">' + item.title + '</li>')
                        $ele.on('click',function(event){
                            var paytype = $(this).data('paytype');

                            justchatApiMgr.agentSendReceipt({
                                pay_type:paytype,
                                player_id:currentTarget
                            },function(res){
                                if(res.status != 0){
                                    layer.msg('账户下发失败！')
                                }
                            },function(){
                                layer.msg('账户下发失败！')
                            })
                            $box.hide();
                            event.stopPropagation();
                            return false;
                        })
                        $box.append($ele);
                    })
                    $('body').on('click',function(){
                        $box.hide();
                    })
                    if($box.children().length>0){
                        var $main = $('.layim-chat-main')
                        // $main.css('bottom','92px;');
                        $main.get(0).scrollTop = $main.get(0).scrollHeight +1000;
                    }

                }
            })
        }

        // 初始化代理快捷回复
        function initAgentQuickReply(){
            if(!isAgency || (currentTarget == officialID)) return
            justchatApiMgr.getQuickReply(function(res){
                if(res.status == 0){
                    var replay = res.data.quick_reply;

                    if(!(replay && replay.length>0)){
                        $('.show-quick-reply-btn').hide()
                        return
                    }
                    var $box = $(".quick-reply-btn-box");

                    $('.show-quick-reply-btn').show().on('click',function(event){
                        $('.send-account-btn-box').hide();
                         $box.css('display', $box.css('display')=='block'?'none':'block')

                         event.stopPropagation();
                         return false;
                    })

                    $box.empty();
                    replay.forEach(function(item,index){
                        var $ele = $('<li class="quick-reply-btn">' + (index+1) + '.'+item.title + '</li>')
                        $ele.on('click',function(event){
                            sendMessage(item.content);
                            $box.hide();
                            event.stopPropagation();
                            return false;
                        })
                        $box.append($ele);
                    })
                    $('body').on('click',function(){
                        $box.hide();
                    })
                    if($box.children().length>0){
                        var $main = $('.layim-chat-main')
                        // $main.css('bottom','92px;');
                        $main.get(0).scrollTop = $main.get(0).scrollHeight +1000;
                    }
                }else{
                    $('.show-quick-reply-btn').hide()
                }
            },function(){
                $('.show-quick-reply-btn').hide()
            })

        }

        //转换时间
        layui.data.date = function (timestamp) {
            var d = new Date(timestamp||new Date());
            return d.getFullYear() + '-' + digit(d.getMonth() + 1) + '-' + digit(d.getDate())
            + ' ' + digit(d.getHours()) + ':' + digit(d.getMinutes());
        };

        //转换内容
        layui.data.content = function (content) {
            //支持的html标签
            var html = function (end) {
                return new RegExp('\\n*\\[' + (end || '') + '(pre|div|p|table|thead|th|tbody|tr|td|ul|li|ol|li|dl|dt|dd|h2|h3|h4|h5)([\\s\\S]*?)\\]\\n*', 'g');
            };
            content = (content || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
                .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;') //XSS
                .replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;">$1</a>$2') //转义@

                .replace(/face\[([^\s\[\]]+?)\]/g, function (face) {  //转义表情
                    var alt = face.replace(/^face/g, '');
                    return '<img alt="' + alt + '" title="' + alt + '" src="' + faces[alt] + '">';
                })
                .replace(/img\[([^\s]+?)\]/g, function (img) {  //转义图片
                    return '<img class="layui-layim-photos" src="' + img.replace(/(^img\[)|(\]$)/g, '') + '">';
                })
                .replace(/file\([\s\S]+?\)\[[\s\S]*?\]/g, function (str) { //转义文件
                    var href = (str.match(/file\(([\s\S]+?)\)\[/) || [])[1];
                    var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
                    if (!href) return str;
                    return '<a class="layui-layim-file" href="' + href + '" download target="_blank"><i class="layui-icon">&#xe61e;</i><cite>' + (text || href) + '</cite></a>';
                })
                .replace(/audio\[([^\s]+?)\]/g, function (audio) {  //转义音频
                    return '<div class="layui-unselect layui-layim-audio" layim-event="playAudio" data-src="' + audio.replace(/(^audio\[)|(\]$)/g, '') + '"><i class="layui-icon">&#xe652;</i><p>音频消息</p></div>';
                })
                .replace(/video\[([^\s]+?)\]/g, function (video) {  //转义音频
                    return '<div class="layui-unselect layui-layim-video" layim-event="playVideo" data-src="' + video.replace(/(^video\[)|(\]$)/g, '') + '"><i class="layui-icon">&#xe652;</i></div>';
                })

                .replace(/a\([\s\S]+?\)\[[\s\S]*?\]/g, function (str) { //转义链接
                    var href = (str.match(/a\(([\s\S]+?)\)\[/) || [])[1];
                    var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
                    if (!href) return str;
                    return '<a href="' + href + '" target="_blank">' + (text || href) + '</a>';
                }).replace(html(), '\<$1 $2\>').replace(html('/'), '\</$1\>') //转移HTML代码
                .replace(/\n/g, '<br>') //转义换行
            return content;
        };

        var elemChatMain = ['<li {{d.payAmount?"data-payAmount="+d.payAmount + " data-payType="+d.payType + " data-receiptAddressId="+d.receiptAddressId:""}} {{d.paytype?"data-paytype="+d.paytype:""}} id="chat-{{d.cid}}" class="layim-chat-li{{ d.mine ? " layim-chat-mine" : " layim-chat-target" }}{{ d.paytype ? " layim-chat-pay":"" }}{{ d.payAmount?" layim-chat-amount":""}}">'
            , '<i class="{{ d.isSendSuccess === false? "layui-icon layui-icon-tips layim-chat-tips":"layui-hide"}}"></i>'
            , '<div class="layim-chat-user" data-userid="{{ d.mine ? "" : d.fromid }}" '
            , isAgency?'layim-event="{{ d.mine ? "" : "openUserInfo" }}">':'>'
            , '<img class="avatar" >'
            , '</div>'
            , '<div class={{ d.msgType == 1 ? "justchat-chat-image" : "layim-chat-text" }}>{{ layui.data.content(d.content||"&nbsp;") }}</div>'
            , '</li>'].join('');

        var officialTemp = ['<li>d.content'
        , '</li>'].join('');

        var elemChatPicMain = ['<li id="chat-{{d.cid}}" class="layim-chat-img layim-chat-li{{ d.mine ? " layim-chat-mine" : " layim-chat-target" }}{{ d.paytype ? " layim-chat-pay":"" }}{{ d.payAmount?" layim-chat-amount":""}}">'
            , '<i class="{{ d.isSendSuccess === false? "layui-icon layui-icon-tips layim-chat-tips":"layui-hide"}}"></i>'
            , '<div class="layim-chat-user" data-userid="{{ d.mine ? "" : d.fromid }}" '
            , isAgency?'layim-event="{{ d.mine ? "" : "openUserInfo" }}">':'>'
            , '<img class="avatar" >'
            , '</div>'
            , '<div class="layim-chat-text"><img class="layui-layim-photos" src="{{ compatibleImgUrl(d.content) }}" onerror="this.onerror="";this.src="../../img/pic_faild.png""></div>'
            , '</li>'].join('');

        //处理初始化信息
        var cache = {message: {}, chat: []}, init = function (options) {
            var init = options.init || {},
                mine = init.mine || {}
                , local = storage.getMyLayimMobile()
                , obj = {
                    base: options
                    , local: local
                    , mine: mine
                    , history: local.history || []
                }, create = function (data) {
                    var mine = data.mine || {};
                    var local = storage.getMyLayimMobile(), historyList = {};

                    if(local.history){
                        var unMsgtotal = 0;
                        Object.keys(local.history).map(hisfriend => {
                            // 初始化发送未读消息数量
                            if(local.history[hisfriend].unMsgNum){
                                unMsgtotal += local.history[hisfriend].unMsgNum;
                            }

                            historyList[hisfriend] = {};
                            if(local.history[hisfriend]["msgType"] =="CUSTOM"){
                                historyList[hisfriend] = local.history[hisfriend];
                                if(historyList[hisfriend]["content"].includes("img")){
                                    historyList[hisfriend] = $.extend(historyList[hisfriend], {"sign": "[图片消息] 点击查看"});
                                }else {
                                    historyList[hisfriend] = $.extend(historyList[hisfriend], {"sign": "[收款信息] 点击充值"});
                                }
                            }else if (local.history[hisfriend]["msgType"] =="IMAGE"){
                                historyList[hisfriend] = $.extend(local.history[hisfriend], {"sign": "[图片消息] 点击查看"});
                            }else {
                                historyList[hisfriend] = local.history[hisfriend];
                            }
                        })

                        window.parent.postMessage({unMsgtotal:unMsgtotal},"*");
                    }

                    var obj = {
                        base: options //基础配置信息
                        , local: local //本地数据
                        , mine: mine //我的用户信息
                        , friend: data.friend || [] //联系人信息
                        , group: data.group || [] //群组信息
                        , history: historyList || [] //历史会话信息
                    };
                    obj.sortHistory = sort(obj.history, 'historyTime');
                    cache = $.extend(cache, obj);

                    if(location.search.includes("chatType=0")){
                        $('body').hide();
                        popim(laytpl(comTpl(elemTpl)).render(obj));
                        // 代理不激活
                        if(!isAgency){
                            initLayimChatSlide()
                        }
                        resetListInfo()
                        initDeleteHistoryItem();

                        var target = JSON.parse(session({
                            type:'get',
                            key:'target'
                        }))

                        // target存在，返回到之前的聊天界面,处理不是一对一的时候，聊天跳转到支付，返回来跑到了列表页面。
                        if(target){
                            currentTarget = target.id
                            popchat(target,-1);
                            setUserInfo(getParam('imid'),function(info){
                                $(".layim-chat-mine .layim-chat-user .avatar").attr('src',info.portraitUri);
                            });
                            setUserInfo(target.id,function(info){
                                $(".layim-chat-target .avatar").attr('src',info.portraitUri);
                                $(".chat-title").text(info.nickname);
                            });

                              // 由于事件监听在后面，轮询查看有没有call.chat。
                            (function (){
                                var i = 1;
                                var num = 50;
                                var active = false;
                                renderType()
                                function renderType(){
                                    if(active) {
                                        i = null;
                                        num = null;
                                        active = null;
                                        renderType = null;
                                        return
                                    }
                                    setTimeout(function(){
                                        if(call.chat){
                                            active = true
                                            layui.each(call.chat, function (index, item) {
                                                item && item('friend'+target.id);
                                            });

                                            setTimeout(function(){
                                                var chatMain = $('.layim-chat-main')
                                                chatMain.scrollTop(chatMain[0].scrollHeight + 1000);
                                            },500)
                                        }else{
                                            if(num <= i){
                                                renderType = null;
                                                return;
                                            };
                                            i++;
                                            renderType();
                                        }
                                    },i==1?200:500);
                                }
                            }())
                        }


                        $('body').show();
                    }
                    layui.each(call.ready, function (index, item) {
                        item && item(obj);
                    });

                    initUI_justchat(unMsgtotal);
                };
            cache = $.extend(cache, obj);
            if (options.brief) {
                return layui.each(call.ready, function (index, item) {
                    item && item(obj);
                });
            }
            create(init)
        };

        //显示好友列表面板
        var layimMain, popim = function (content) {
            return layer.open({
                type: 1
                , shade: false
                , shadeClose: false
                , anim: -1
                , content: content
                , success: function (elem) {
                    layimMain = $(elem);
                    fixIosScroll(layimMain.find('.layui-layim'));
                    if (cache.base.tabIndex) {
                        events.tab($('.layui-layim-tab>li').eq(cache.base.tabIndex));
                    }
                }
            });
        };

        //弹出公共面板
        var popPanel = function (options, anim) {
            options = options || {};
            var data = $.extend({}, cache, {
                title: options.title || ''
                , data: options.data
            });
            return layer.open({
                type: 1
                , shade: false
                , shadeClose: false
                , anim: -1
                , content: laytpl(comTpl(options.tpl, anim === -1 ? false : true, true)).render(data)
                , success: function (elem) {
                    var othis = $(elem);
                    othis.prev().find('.layim-panel').addClass('layui-m-anim-lout');
                    options.success && options.success(elem);
                    options.isChat || fixIosScroll(othis.find('.layim-content'));
                }
                , end: options.end
            });
        };

        function toggelSendBtn() {
            var $input = $('input.justchat-amount-input');
            if($input.val()===''){
                $input.siblings('.layim-send').addClass('layui-hide layui-disabled');
                $input.siblings('.layim-tool-toggle').removeClass('layui-hide');
            }else{
                $input.siblings('.layim-send').removeClass('layui-hide layui-disabled');
                $input.siblings('.layim-tool-toggle').addClass('layui-hide');
            }
        }


        //弹出聊天面板
        var popChatPanel = function (options, anim) {
            options = options || {};
            var data = $.extend({}, cache, {
                title: options.title || ''
                , data: options.data
            });
            return layer.open({
                type: 1
                , shade: false
                , shadeClose: false
                , anim: -1
                , content: laytpl(chatTpl(options.tpl, anim === -1 ? false : true, true)).render(data)
                , success: function (elem) {
                    var othis = $(elem);
                    othis.prev().find('.layim-panel').addClass('layui-m-anim-lout');
                    options.success && options.success(elem);
                    options.isChat || fixIosScroll(othis.find('.layim-content'));
                }
                , end: options.end
            });
        };

        //显示聊天面板
        var layimChat, layimMin, To = {};
        function popchat(data, anim, back) {
            // debugger;
            data = data || {};

            if (!data.id) {
                return layer.msg('非法用户');
            }

            layer.close(popchat.index);

            return popchat.index = popChatPanel({
                tpl: elemChatTpl
                , data: data
                , title: data.name
                , isChat: !0
                , success: function (elem) {

                    layimChat = $(elem);

                    hotkeySend();
                    viewChatlog();

                    delete cache.message[data.type + data.id]; //剔除缓存消息

                    storage.updateHistoryById({
                        id:data.id,
                        key:'unMsgNum',
                        value:0
                    })

                    if(isAgency){
                        var unMsgtotal = countAllUnMsg();
                        window.parent.postMessage({unMsgtotal:unMsgtotal},"*");
                    }

                    //聊天窗口的切换监听
                    var thatChat = thisChat(), chatMain = thatChat.elem.find('.layim-chat-main');
                    layui.each(call.chatChange, function (index, item) {
                        item && item(thatChat);
                    });

                    layui.each(call.chatloaded, function (index, item) {
                        item && item(thatChat);
                    });

                    fixIosScroll(chatMain);

                    //输入框获取焦点
                    thatChat.textarea.on('focus', function () {
                        $(".layim-chat-footer .layui-layim-face").remove();
                        $('.layim-chat-footer .layim-tool-face').html('&#xe60c;')
                        $(".layim-chat-tool").addClass('layui-hide');
                        setTimeout(function () {
                            chatMain.scrollTop(chatMain[0].scrollHeight + 1000);
                        }, 500);
                    });
                }
                , end: function () {
                    layimChat = null;
                    sendMessage.time = 0;
                }
            }, anim);

        };

        //修复IOS设备在边界引发无法滚动的问题
        var fixIosScroll = function (othis) {
            if (device.ios) {
                othis.on('touchmove', function (e) {
                    var top = othis.scrollTop();
                    if (top <= 0) {
                        othis.scrollTop(1);
                        e.preventDefault(e);
                    }
                    if (this.scrollHeight - top - othis.height() <= 0) {
                        othis.scrollTop(othis.scrollTop() - 1);
                        e.preventDefault(e);
                    }
                });
            }
        };

        //获取当前聊天面板
        var thisChat = function () {
            if (!layimChat) return {};
            var cont = layimChat.find('.layim-chat');
            var to = JSON.parse(decodeURIComponent(cont.find('.layim-chat-tool').data('json')));
            delete to['avatar'];
            return {
                elem: cont
                , data: to
                , textarea: cont.find('input.justchat-amount-input')
            };
        };

        //将对象按子对象的某个key排序
        var sort = function (data, key, asc) {
            var arr = []
                , compare = function (obj1, obj2) {
                var value1 = obj1[key];
                var value2 = obj2[key];
                if (value2 < value1) {
                    return -1;
                } else if (value2 > value1) {
                    return 1;
                } else {
                    return 0;
                }
            };
            layui.each(data, function (index, item) {
                arr.push(item);
            });
            arr.sort(compare);
            if (asc) arr.reverse();
            return arr;
        };


        function initUI_justchat(num) {
            //重置标题栏背景 (直接改源码对应的标题颜色)
            //$(".layim-title").css("background-color", "#2a80fc");
            var unReadHtml = '<span class="chat-title">消息</span><span class="justchat-status">('+num+')</span>'

            $("#layui-m-layer0 .layim-chat-status")
                .css("position", "relative")
                .css("display", "block")
                .css("text-align","center")
                .css("font-color", "#ffffff")
                .css("font-size", "18px")
                .css("opacity", "1")
                .html(num > 0 ? unReadHtml : '<span class="chat-title">消息</span><span class="justchat-status"></span>');
            $(".layui-layim-tab").hide();
        };

        // 计算当前用户的所有的未读消息数量
        function countAllUnMsg() {
            var unMsgtotal = 0;
            var historys = storage.getAllHistory();
            // 计算所有未读消息数量
            for(var key in historys){
                if(historys[key].unMsgNum){
                    unMsgtotal += historys[key].unMsgNum;
                }
            }
            return unMsgtotal;
        }

        //记录历史会话
        var setHistory = function (data,isSendBySelf) {

            var local = storage.getMyLayimMobile();
            var obj = {}, history = local.history || {};
            var layimMain = $("#layui-m-layer0");

            if (!layimMain) return;

            var historyElem = layimMain.find('.layim-list-history');

            data.historyTime = new Date().getTime();
            data.timestamp = new Date().getTime();
            data.time = layui.data.date();

            if(data.msgType =="CUSTOM"){
                if(data.content.includes("img")){
                    data.sign = "[图片消息] 点击查看"
                }else {
                    data.sign = "[收款信息] 点击查看"
                }
            } else if(data.msgType =="IMAGE"){
                data.sign = "[图片消息] 点击查看"
            } else {
                // 非官方运营
                if(data.id != officialID){
                    data.sign = data.content;
                }
            }

            var $title = $('.layim-chat-status .chat-title');

            if(imid == data.fromid){
              isSendBySelf = true
            }

            // 别人发的信息，并且没在聊天面板，或者在聊天面板，消息不是当前正在聊天的对象，或者控制台的iframe没打开，才记录未读消息。
            if(!isSendBySelf && ($title.length == 0 || (data.id!=currentTarget))){
                // 保存未读信息数量到本地
                var unMsgNum = (history[data.type + data.id] && history[data.type + data.id].unMsgNum || 0) + 1;
                data.unMsgNum = unMsgNum;
            }

            // 如果正在聊天，清空与这个人的未读消息。
            if($title.length>0 && (data.id==currentTarget)){
                data.unMsgNum = 0
            }

            // 是否是自己发的消息
            data.mine = isSendBySelf;

            history[data.type + data.id] = data;

            local.history = history;

            layui.data('layim-mobile', {
                key: cache.mine.id
                , value: local
            });

            var unMsgData = [{
                id:data.id,
                msgContext:data.sign,
                nickname:data.username,
                msgNum:data.unMsgNum,
                cid:data.cid
            }]

            // 计算所有未读消息数量
            var unMsgtotal = countAllUnMsg();

            if(historyElem.length>0){
                var msgItem = historyElem.find('.layim-' + data.type + data.id)
                // , msgNums = (cache.message[data.type + data.id] || []).length //未读消息数
                , showMsg = function () {

                    msgItem = historyElem.find('.layim-' + data.type + data.id);
                  
                    if(msgItem.find(".avatar").indexOf('base64')){
                      setUserInfo(data.id,function(info){
                        msgItem.find(".avatar").attr('src',info.portraitUri);
                      })
                    }
                    // setUserInfo(data.id,function(info){
                    //     var $name = msgItem.find(".name");
                    
                    //     $name.text(info.nickname);
                    //     msgItem.find(".avatar").attr('src',info.portraitUri);
                    // })
                    msgItem.removeClass('layim-chat-mine');


                    msgItem.find('p').text(data.sign);

                    msgItem.find('.justchat-multiple-time').text(getMessageDate(data.time));
                    if (unMsgNum > 0) {
                        msgItem.find('.layim-msg-status').html(unMsgNum).addClass(SHOW);
                    }
                };

                if(msgItem.length>0){
                    showMsg();
                    historyElem.prepend(msgItem.clone());
                    msgItem.remove();
                }else {
                    obj[data.type + data.id] = data;
                    var historyList = laytpl(listTpl({
                        type: 'history'
                        , item: 'd.data'
                    })).render({data: obj});
                    historyElem.prepend(historyList);
                    showMsg();
                    historyElem.find('.layim-null').remove();
                }

                initUI_justchat(unMsgtotal)
            }

            // 非自己发送，才通知未读消息
            if(!isSendBySelf){
                window.parent.postMessage({"unreadyMsg": unMsgData,unMsgtotal:unMsgtotal},"*");
            }

            // 在聊天面板，每次发送消息，则刷新自己头像
            if($title.length>0 && (isSendBySelf==true)){
                setUserInfo(getParam('imid'),function(info){
                    $(".layim-chat-mine .layim-chat-user .avatar").attr('src',info.portraitUri);
                })
            }

        };


        var uuid = function () {
            var s = [];
            var hexDigits = "0123456789abcdef";
            for (var i = 0; i < 36; i++) {
                s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
            }
            s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
            s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
            s[8] = s[13] = s[18] = s[23] = "-";

            var uuid = s.join("");
            return uuid;
        };

        var renderPayTypes = function (payTypeHtml) {
            var thatChat = thisChat(), divPayTypes = null;
            try {
                divPayTypes = thatChat.elem.find('.justchat-pay-types')
                divPayTypes.append(payTypeHtml);
            } catch(err) {
                setTimeout(function(){
                    renderPayTypes(payTypeHtml)
                }, 600);
                //处理错误
            }
        };

        //发送消息 justchat customer
        var sendPayAmountMessage = function (amount, receiptAddressId, payType) {
            var data = {
                username: cache.mine ? cache.mine.username : '访客'
                // , avatar: cache.mine ? cache.mine.avatar : (layui.cache.dir + 'css/pc/layim/skin/logo.jpg')
                , id: cache.mine ? cache.mine.id : null
                , mine: true
            };
            var thatChat = thisChat(), ul = thatChat.elem.find('.layim-chat-main ul');
            var To = thatChat.data, maxLength = cache.base.maxLength || 3000;
            var time = new Date().getTime(), textarea = thatChat.textarea;
            // {"type":"pay:select_pay_amount","data":{"receiptAddressId":8,"payType":5,"amount":500000}}

            data.content = (parseInt(amount)/100).toString();

            if (data.content === '') return;

            if (time - (sendMessage.time || 0) > 60 * 1000 * 5) {
                ul.append('<li class="layim-chat-system"><span>' + getMessageDate(layui.data.date()) + '</span></li>');
                sendMessage.time = time;
            }

            var cid = uuid();
            data.cid = cid;

            data.payAmount = amount;
            data.receiptAddressId = amount;
            data.payType = payType;

            ul.append(laytpl(elemChatMain).render(data));

            var lastMsg = $(".layim-chat-main ul li:last-child")
            if(lastMsg.hasClass("layim-chat-mine")){
                if(socketState === 'close'){
                    lastMsg.prepend('<i class="layui-icon layui-icon-tips layim-chat-tips"></i>')
                }else{
                    lastMsg.prepend('<i class="layui-icon layui-icon-loading layim-chat-loading"></i>')
                }
            }

            var param = {
                mine: data
                , to: To
                , cid: cid
            }, message = {
                username: param.mine.username
                // , avatar: param.mine.avatar
                , id: To.id
                , type: To.type
                , msgid: -1
                , cid: cid
                , content: JSON.stringify({
                    type:"pay:select_pay_amount",
                    data:{
                        receiptAddressId:receiptAddressId,
                        payType:payType,
                        amount:amount
                    }
                })
                , mine: true
                , fromid: param.mine.id
                , timestamp: time
                , time: layui.data.date(time)
                , msgType: "CUSTOM"
                , payAmount: amount
                , receiptAddressId: receiptAddressId
                , payType: payType
                , isSendSuccess: false
            };

            // 添加超时监听
            addSendMessageTimer(cid);

            pushChatlog(message);
            layui.each(call.sendPayAmountMessage, function (index, item) {
                item && item(message);
            });
            To.isSendSuccess = false
            To.content = data.content;
            setHistory(To,true);
            chatListMore();
            textarea.val('');
            // textarea.next().addClass('layui-disabled');
            toggelSendBtn()
        };

        //发送消息 justchat customer
        var sendPayTypeMessage = function (paytype) {
            var data = {
                username: cache.mine ? cache.mine.username : '访客'
                // , avatar: cache.mine ? cache.mine.avatar : (layui.cache.dir + 'css/pc/layim/skin/logo.jpg')
                , id: cache.mine ? cache.mine.id : null
                , mine: true
            };

            var thatChat = thisChat(), ul = thatChat.elem.find('.layim-chat-main ul');
            var To = thatChat.data, maxLength = cache.base.maxLength || 3000;
            var time = new Date().getTime(), textarea = thatChat.textarea;
            data.content = PAY_TYPE_NAME[paytype];
            if (data.content === '') return;

            if (time - (sendMessage.time || 0) > 60 * 1000 * 5) {
                ul.append('<li class="layim-chat-system"><span>' + getMessageDate(layui.data.date()) + '</span></li>');
                sendMessage.time = time;
            }

            var cid = uuid();
            data.cid = cid;
            data.paytype = paytype

            ul.append(laytpl(elemChatMain).render(data));

            var lastMsg = $(".layim-chat-main ul li:last-child")
            if(lastMsg.hasClass("layim-chat-mine")){
                if(socketState === 'close'){
                    lastMsg.prepend('<i class="layui-icon layui-icon-tips layim-chat-tips"></i>')
                }else{
                    lastMsg.prepend('<i class="layui-icon layui-icon-loading layim-chat-loading"></i>')
                }
            }

            var param = {
                mine: data
                , to: To
                , cid: cid
            }, message = {
                username: param.mine.username
                // , avatar: param.mine.avatar
                , id: To.id
                , type: To.type
                , msgid: -1
                , cid: cid
                , content: PAY_TYPE_NAME[paytype]
                , mine: true
                , fromid: param.mine.id
                , timestamp: time
                , time: layui.data.date(time)
                , msgType: "CUSTOM"
                , paytype: paytype
                , isSendSuccess: false
            };

            // 添加超时监听
            addSendMessageTimer(cid);

            pushChatlog(message);
            layui.each(call.sendPayTypeMessage, function (index, item) {
                item && item(message);
            });
            To.isSendSuccess = false
            To.content = data.content;
            setHistory(To,true);
            chatListMore();
            textarea.val('');
            // textarea.next().addClass('layui-disabled');
            toggelSendBtn()
        };
        //发送消息 常规
        function sendMessage(SendMessage) {
            var data = {
                username: cache.mine ? cache.mine.username : '访客'
                // , avatar: cache.mine ? cache.mine.avatar : (layui.cache.dir + 'css/pc/layim/skin/logo.jpg')
                , id: cache.mine ? cache.mine.id : null
                , mine: true
                , msgType: 0
            };
            var thatChat = thisChat(), ul = thatChat.elem.find('.layim-chat-main ul');

            var To = thatChat.data, maxLength = cache.base.maxLength || 3000;

            var time = new Date().getTime(), textarea = thatChat.textarea;
            if(SendMessage){data.content =SendMessage;}
            else{
                data.content = textarea.val();}


            if (data.content === '') return;

            if (data.content.length > maxLength) {
                return layer.msg('内容最长不能超过' + maxLength + '个字符')
            }

            var cid = uuid();

            if (time - (sendMessage.time || 0) > 60 * 1000 * 5) {
                ul.append('<li class="layim-chat-system"><span>' + getMessageDate(layui.data.date()) + '</span></li>');
                sendMessage.time = time;
            }

            data.cid = cid;
            ul.append(laytpl(elemChatMain).render(data));

            var lastMsg = $(".layim-chat-main ul li:last-child")
            if(lastMsg.hasClass("layim-chat-mine")){
                if(socketState === 'close'){
                    lastMsg.prepend('<i class="layui-icon layui-icon-tips layim-chat-tips"></i>')
                }else{
                    lastMsg.prepend('<i class="layui-icon layui-icon-loading layim-chat-loading"></i>')
                }
            }

            var info = data.content;
            var msgType = "TEXT";
            // if (info.startsWith("img[http")) {
            //     msgType = "IMAGE";
            // }


            var param = {
                mine: data
                , to: To
                , cid: cid
            }, message = {
                username: param.mine.username
                // , avatar: param.mine.avatar
                , id: To.id
                , type: To.type
                , msgid: -1
                , cid: cid
                , content: param.mine.content
                , mine: true
                , fromid: param.mine.id
                , timestamp: time
                , time: layui.data.date(time)
                , msgType: msgType
                , isSendSuccess: false
            };

            // 添加超时监听
            addSendMessageTimer(cid);

            pushChatlog(message);
            layui.each(call.sendMessage, function (index, item) {
                item && item(param);
            });
            To.isSendSuccess = false
            To.content = data.content;
            To.msgType = msgType;
            setHistory(To,true);
            chatListMore();
            textarea.val('');

            // textarea.next().addClass('layui-disabled');
            toggelSendBtn()
        };

        // 发送图片
        function sendPicToChat(url,cid) {
            var content = url;

            var data = {
                username: cache.mine ? cache.mine.username : '访客'
                // , avatar: cache.mine ? cache.mine.avatar : (layui.cache.dir + 'css/pc/layim/skin/logo.jpg')
                , id: cache.mine ? cache.mine.id : null
                , mine: true
                , msgType: 1
            };
            var thatChat = thisChat(), ul = thatChat.elem.find('.layim-chat-main ul');

            var To = thatChat.data, maxLength = cache.base.maxLength || 3000;
            var time = new Date().getTime();
            data.content = content;
            data.cid = cid;

            var $chat = $('#chat-'+cid);

            var lastMsg = $(".layim-chat-main ul li:last-child")
            // 非重发，更新dom
            if($chat.length > 0){
                $chat.find('.layui-layim-photos').attr('src',compatibleImgUrl(url));
                if(socketState === 'close'){
                    $chat.find('.layim-chat-loading').remove();
                    lastMsg.prepend('<i class="layui-tips-msgTypeImg layui-icon layui-icon-tips layim-chat-tips"></i>')
                }
            }
            // 重发
            else{
                if (time - (sendMessage.time || 0) > 60 * 1000 * 5) {
                    ul.append('<li class="layim-chat-system"><span>' + getMessageDate(layui.data.date()) + '</span></li>');
                    sendMessage.time = time;
                }
                ul.append(laytpl(elemChatPicMain).render(data));
                if(lastMsg.hasClass("layim-chat-mine")){
                    if(socketState === 'close'){
                        lastMsg.prepend('<i class="layui-tips-msgTypeImg layui-icon layui-icon-tips layim-chat-tips"></i>')
                    }else{
                        lastMsg.prepend('<i class="layui-icon layui-icon-loading layim-chat-loading"></i>')
                    }
                }
            }

            var msgType = "IMAGE";

            var param = {
                mine: data
                , to: To
                , cid: cid
            }, message = {
                username: param.mine.username
                // , avatar: param.mine.avatar
                , id: To.id
                , type: To.type
                , msgid: -1
                , cid: cid
                , content: content
                , mine: true
                , fromid: param.mine.id
                , timestamp: time
                , time: layui.data.date(time)
                , msgType: msgType
                , isSendSuccess: false
            };

            // 添加超时监听
            addSendMessageTimer(cid);

            pushChatlog(message);

            To.isSendSuccess = false
            To.content = data.content;
            To.msgType = msgType;
            setHistory(To,true)

            layui.each(call.sendMessage, function (index, item) {
                item && item(param);
            });
        };

        // 在图片上传前
        function beforePicUpload(cid){
            var content = 'local[../../img/pic_faild.png]';

            var data = {
                username: cache.mine ? cache.mine.username : '访客'
                // , avatar: cache.mine ? cache.mine.avatar : (layui.cache.dir + 'css/pc/layim/skin/logo.jpg')
                , id: cache.mine ? cache.mine.id : null
                , mine: true
                , msgType: 1
            };
            var thatChat = thisChat(), ul = thatChat.elem.find('.layim-chat-main ul');

            var To = thatChat.data, maxLength = cache.base.maxLength || 3000;
            var time = new Date().getTime();
            data.content = content;

            if (time - (sendMessage.time || 0) > 60 * 1000 * 5) {
                ul.append('<li class="layim-chat-system"><span>' + getMessageDate(layui.data.date()) + '</span></li>');
                sendMessage.time = time;
            }

            data.cid = cid;

            ul.append(laytpl(elemChatPicMain).render(data));

            var lastMsg = $(".layim-chat-main ul li:last-child")
            if(lastMsg.hasClass("layim-chat-mine")){
                if(socketState !== 'close'){
                    lastMsg.prepend('<i class="layui-icon layui-icon-loading layim-chat-loading"></i>')
                }
            }


            // 优化,图片加载完成后滚动到底部
            var $pic = $('#chat-'+cid).find('.layui-layim-photos');
            $pic.on('load',function(){
                var main = $('.layim-chat-main ').get(0);
                main.scrollTop = main.scrollHeight + 1000;
                $pic.off('load');
            })


            var msgType = "IMAGE";

            var message = {
                username: data.username
                // , avatar: data.avatar
                , id: To.id
                , type: To.type
                , msgid: -1
                , cid: cid
                , content: content
                , mine: true
                , fromid: data.id
                , timestamp: time
                , time: layui.data.date(time)
                , msgType: msgType
                , isSendSuccess: 'ignore'
            };


            pushChatlog(message);

            To.isSendSuccess = 'ignore'
            To.content = data.content;
            To.msgType = msgType;
            setHistory(To,true)
        }

        //消息声音提醒
        var voice = function () {
            var audio = document.createElement("audio");
            audio.src = layui.cache.dir + 'css/modules/layim/voice/' + cache.base.voice;
            audio.play();
        };

        // 是否重复
        function isDuplicate(data,target_id) {
            // 检查最后5条
            var rule = 5;

            var chatlog = storage.getChatlogById(target_id)
            var len = chatlog.length;
            if(len == 0) return false

            for(var j=len-1;j>=(len-1-rule>0?len-1-rule:0);j--){
                if(chatlog[j].msgid == data.msgid){
                    return true
                }
            }
            return false
        }

        // confirm弹窗
        function popConfirm(obj){
            var content = obj.content;
            var ok = obj.ok;
            var cancel = obj.cancel;

            var $body = $("body")
                $layer = $(`<div id="isClearHistoryLayer" style="position:fixed;left:0;top:0;width:100%;height:100%;z-index:198910140;background:rgba(0,0,0,.5)">
                <div  style="left:calc(50% - 140px);top:calc(50% - 75px);position:absolute;width:280px;min-height:150px;box-sizing:border-box;background:#fff;padding:30px 40px;">
                    <p style="margin-bottom:20px;font-size:16px;text-align:center">${content}</p>
                    <div style="text-align:center;">
                        <button  style="margin-left:0px;height:36px;line-height:30px;padding:2px 20px;" class="cancel-btn layui-btn layui-btn-primary">取消</button>
                        <button style="height:36px;line-height:30px;margin-left:20px;padding:2px 20px;" class="confirm-btn layui-btn">确定</button>
                    </div>
                </div>
                </div>`);

                $layer.appendTo($body);

                var $cancelBtn = $("#isClearHistoryLayer .cancel-btn");
                var $confimBtn = $("#isClearHistoryLayer .confirm-btn");
                $cancelBtn.on('click',function(){
                    $layer.remove();
                    cancel && cancel()
                })
                $confimBtn.on('click',function(){
                    ok && ok();

                    $layer.remove();
                })
        }

        // 初始化聊天历史消息的滑动，并且激活删除聊天。
        function initLayimChatSlide(){
            var startX = 0;
            var endX = 0;
            var distance = 50;
            var $ul = $(".layim-list-history");
            var $li = null;
            $ul.on("touchstart",function(e){
                $li = null;
                startX = 0;
                endX = 0;
                var $target = $(e.target);
                $li = getli($target);
                if(!$li) return
                startX = e.touches['0'].clientX;
            })

            $ul.on("touchend",function(e){
                var $target = $(e.target);
                var $endLi = getli($target);
                // 没有点在li上，或者开始和结束的li不一样，则不做滑动。
                if(!$li || ($li.attr('class') !== $endLi.attr('class'))) return
                endX = e.changedTouches['0'].clientX;
                countSlide()
            })

            initDeleteHistoryItem();

            function isul($target){
                return $target.hasClass('layim-list-history')
            }
            function getli($target){
                if(isul($target)) return null
                if($target.get(0).tagName.toLowerCase() === 'li') return $target
                return $target.closest('li')
            }
            function countSlide(){
                if(Math.abs(startX - endX)<distance) return
                // 左滑动
                if(startX > endX){
                    $li.addClass('layim-li-more');
                }else{
                    $li.removeClass('layim-li-more');
                }
            }

            // 激活删除聊天
            function initDeleteHistoryItem(){
                $ul.on("click",function(e){
                    e.stopPropagation();
                    var $target = $(e.target);
                    if(!$target.hasClass('delete-layim-chat-li')) return
                    var targetName = $target.closest('li').find('.name').text();
                    popConfirm({
                        content:'确定删除与【'+targetName+'】的对话？',
                        ok:function(){
                            var targetId = $target.data('targetid');
                            storage.deleteChatlog({
                                id:targetId
                            })
                            storage.deleteHistory({
                                id:targetId
                            })
                            $target.closest('li').remove();

                            var isEmpty = true
                            for(var key in storage.getAllHistory()){
                                isEmpty = false;
                                break;
                            }
                            if(isEmpty){
                                $ul.append('<li class="layim-null">当前无消息</li>')
                            }

                            var unMsgNum = countAllUnMsg();
                            initUI_justchat(unMsgNum);
                            if(isAgency){
                                window.parent.postMessage({unMsgtotal:unMsgNum},"*");
                            }

                        }
                    })
                })
            }
        }

        // 设置用户的信息,先展示默认头像，自己的头像加载完才显示
        function setUserInfo(id,callback){
            if(!id) return

            var friendsInfo = JSON.parse(localStorage.getItem("friendsInfo")) || {};
            if(friendsInfo[id]){
                var url = friendsInfo[id].portraitUri;
                // 自己时代理，或者对方是代理，用代理默认链接
                if((isAgency && (imid==id)) || (!isAgency && (imid != id))){ //
                    friendsInfo[id].portraitUri = agentDefultImg;
                }else{
                    friendsInfo[id].portraitUri = playerDefultImg;
                }
                if(id == officialID){
                    friendsInfo[id].portraitUri = officialDefultImg
                }
                callback(friendsInfo[id]);
                if(url && (url != agentDefultImg) && (url != playerDefultImg) && (url != officialDefultImg) && (url != 'http://image.barchain.net/1558000605371.jpg') && (url != 'http://image.barchain.net/1558776964789.png')){
                    (function(callback){
                        getOnloadImg(url,function(){
                            friendsInfo[id].portraitUri = url;
                            callback(friendsInfo[id]);
                            callback = null
                        })
                    })(callback)
                }
                return
            }
            var onSucceedCallback = function (result) {
                if(result.status ==0){
                    var imid = getParam('imid');
                    var url = result.data.portraitUri;
                    friendsInfo[id] = JSON.parse(JSON.stringify(result.data));
                    if(!url){
                        if((isAgency && (imid==id)) || (!isAgency && (imid != id))){ //
                            url = agentDefultImg;
                        }else{
                            url = playerDefultImg;
                        }
                        if(id == officialID){
                            url = officialDefultImg
                        }
                    }
                    friendsInfo[id].portraitUri = result.data.portraitUri;
                    localStorage.setItem('friendsInfo', JSON.stringify(friendsInfo))

                    // 自己时代理，或者对方是代理，用代理默认链接
                    if((isAgency && (imid==id)) || (!isAgency && (imid != id))){ //
                        result.data.portraitUri = agentDefultImg;
                    }else{
                        result.data.portraitUri = playerDefultImg;
                    }
                    if(id == officialID){
                        result.data.portraitUri = officialDefultImg
                    }

                    callback(result.data);
                    if(url && (url != agentDefultImg) && (url != playerDefultImg) && (url != officialDefultImg) && (url != 'http://image.barchain.net/1558000605371.jpg') && (url != 'http://image.barchain.net/1558776964789.png')){
                        (function(callback){
                            getOnloadImg(url,function(){
                                friendsInfo[id].portraitUri = url;
                                callback(friendsInfo[id]);
                                callback = null;
                            })
                        })(callback)
                    }

                } else {
                    layer.msg('连接异常')
                }
            };
            var onErrorCallback = function () {
                layer.msg('连接异常')
            };

            justchatApiMgr.getUserInfo(id, onSucceedCallback, onErrorCallback);

        }

        function getOnloadImg(url,cb){
            var img = new Image();
            img.src = url;
            img.onload = function(){
                cb(url)
                img = null;
            }
        }

        // 重置列表头像和名字
        function resetListInfo(){

            var imid = getParam('imid');
            // 设置头像和名字信息,别人发送的
            var local = JSON.parse(localStorage.getItem('layim-mobile')) || {}
            if(local[imid] && local[imid]['history']){
                var his = local[imid]['history']
                for(var key in his){
                    var hisItem = his[key];
                    setUserInfo(hisItem.id,function(info){
                        var $ele = $(".layim-chat-friend"+info.id);
                        $ele.find(".name").text(info.nickname);
                        $ele.find(".avatar").attr('src',info.portraitUri);
                    })
                }

            }
        }

        //接受消息
        var getMessage = function (data) {
            var target_id = data.id;

            // 重复则忽略
            if(isDuplicate(data,target_id)) return

            data = data || {};

            var  thatChat = thisChat(), thisData = thatChat.data || {}
                , isThisData = thisData.id == data.id && thisData.type == data.type; //是否当前打开联系人的消息

            data.timestamp = data.timestamp || new Date().getTime();

            data.system || pushChatlog(data);
            // messageNew = JSON.parse(JSON.stringify(data));

            if (cache.base.voice) {
                voice();
            }

            if ((!layimChat && data.content) || !isThisData) {
                if (cache.message[data.type + data.id]) {
                    cache.message[data.type + data.id].push(data)
                } else {
                    cache.message[data.type + data.id] = [data];
                }
            }

            var newData = {}
            if(data.mine){
                var friendsInfo = JSON.parse(localStorage.getItem("friendsInfo")) || {};
                if(friendsInfo[data.id]){
                    newData = $.extend({}, data, {
                        name: friendsInfo[data.id]['nickname'],
                        username: friendsInfo[data.id]['nickname'],
                        // avatar: friendsInfo[data.id]['portraitUri']
                    })
                    setHistory(newData,true);
                } else {
                    var onSucceedCallback = function (result) {
                        if(result.status ==0){
                            // if(!(result.data.portraitUri)){
                            //     if(isAgency){ //
                            //         result.data.portraitUri = agentDefultImg;
                            //     }else {
                            //         result.data.portraitUri = playerDefultImg;
                            //     }
                            // }
                            newData = $.extend({}, data, {
                                name: result.data.nickname,
                                username: result.data.nickname,
                                // avatar: result.data.portraitUri
                            })
                            friendsInfo[data.id] = result.data
                            localStorage.setItem('friendsInfo', JSON.stringify(friendsInfo))
                            setHistory(newData,false);
                        } else {
                            layer.msg('连接异常')
                        }
                    };
                    var onErrorCallback = function () {
                        layer.msg('连接异常')
                    };
                    justchatApiMgr.getUserInfo(data.id, onSucceedCallback, onErrorCallback)
                }
            } else {
                newData = data
                setHistory(newData,false);
            }

            // 判断是否在1v1聊天中，如果不是则不往下执行。
            if (!layimChat || !isThisData) return;

            var cont = layimChat.find('.layim-chat')
                , ul = cont.find('.layim-chat-main ul');

            //系统消息
            if (data.system) {
                ul.append('<li class="layim-chat-system"><span>' + data.content + '</span></li>');
            } else if (data.content.replace(/\s/g, '') !== '') {
                if (data.timestamp - (sendMessage.time || 0) > 60 * 1000 * 5) {
                    ul.append('<li class="layim-chat-system"><span>' + getMessageDate(layui.data.date(data.timestamp)) + '</span></li>');
                    sendMessage.time = data.timestamp;
                }
                if(data.mine){
                    // data = $.extend(data, {username: cache.mine.username,avatar:cache.mine.avatar})
                    data = $.extend(data, {username: cache.mine.username})
                }

                if (data.msgType == "IMAGE"){
                    ul.append(laytpl(elemChatPicMain).render(data));
                }else if (data.msgType == "CUSTOM" && data.mine == isAgency) {
                    var info = data.content;
                    var json_info = JSON.parse(info);
                    var type = json_info.type;
                    if (type == "pay:get_pay_type_amount_levels") {
                        ul.append(laytpl(elemChatCustomAmountLevel).render(data));
                    } else if (type == "pay:get_pay_type_detail") {
                        data.PAY_TYPE_NAME = PAY_TYPE_NAME;
                        data.PAY_TYPE_CLASS_NAME = PAY_TYPE_CLASS_NAME;
                        ul.append(laytpl(elemChatCustomPayDetail).render(data));
                    } else if (type == "get_pay_order_detail") {
                        data.PAY_TYPE_NAME = PAY_TYPE_NAME;
                        data.PAY_TYPE_CLASS_NAME = PAY_TYPE_CLASS_NAME;
                        ul.append(laytpl(elemChatCustomPayDetail).render(data));
                    } else {
                    }
                } else {
                    if(data.msgType == "CUSTOM" && data.content.includes('{')){
                        var json_info = JSON.parse(data.content);
                        var type = json_info.type;
                        var selectpay = json_info.data;
                        if(type== "pay:select_pay_type"){
                            data.content = PAY_TYPE_NAME[selectpay.payType]
                            ul.append(laytpl(elemChatMain).render(data));
                        } else if(type== "pay:select_pay_amount"){
                            data.content = (selectpay.amount/100).toString()
                            ul.append(laytpl(elemChatMain).render(data));
                        }
                    } else {
                        // 官网运营
                        if(data.fromid == officialID){
                            ul.append($(`<li class="official-info-item">${item.content}</li>`))
                            $('.layim-chat form').hide();
                            $('#go-complaint').hide();
                        }
                        else{
                            // 普通消息
                            ul.append(laytpl(elemChatMain).render(data));
                        }
                    }
                }
            }

            var isMine = data.mine;

             // 在聊天面板，接受到消息，如果消息是对方的，则刷新对方头像，如果消息是自己的，则刷新自己的头像
            var $title = $('.layim-chat-status .chat-title');
            if($title.length>0){
                if((!isMine)){
                    setUserInfo(currentTarget,function(info){
                        $(".layim-chat-target .avatar").attr('src',info.portraitUri);
                    })
                }else{
                    setUserInfo(getParam('imid'),function(info){
                        $(".layim-chat-mine .layim-chat-user .avatar").attr('src',info.portraitUri);
                    })
                }
            }

            chatListMore();
        };

        //存储最近MAX_ITEM条聊天记录到本地
        var pushChatlog = function (message) {
            var local = storage.getMyLayimMobile();
            var chatlog = local.chatlog || {};
            var history = local.history || {};
            if (chatlog[message.type + message.id]) {
                chatlog[message.type + message.id].push(message);
                if (chatlog[message.type + message.id].length > MAX_ITEM) {
                    chatlog[message.type + message.id].shift();
                }
            } else {
                chatlog[message.type + message.id] = [message];
            }

            if(message.id){
                history[message.type + message.id] = $.extend({},history[message.type + message.id],message);
            }
            local.chatlog = chatlog;

            layui.data('layim-mobile', {
                key: cache.mine.id
                , value: local
            });
        };

        //justchat CUSTOM 模版
        var elemChatCustomAmountLevel = ['<li class="layim-chat-li{{ d.mine ? " layim-chat-mine" : " layim-chat-target" }}">'
            , '<div class="layim-chat-user" data-userid="{{ d.fromid }}" '
            , isAgency?'layim-event="{{ d.mine ? "" : "openUserInfo" }}">':'>'
            , '<img class="avatar" >'
            , '</div>'
            , '<div class="layim-chat-text">'
            , '{{# var info = d.content; var json_info = JSON.parse(info);var type = json_info.type;var data = json_info.data; }}'
            , '{{# if(data.amountAllowCustom) {  }}'
            , '<div style="margin-bottom: 10px;">请点击下方按钮选择或输入充值金额。</div>'
            , '{{# } else { }}'
            , '<div style="margin-bottom: 10px;">请点击下方按钮选择充值金额。</div>'
            , '{{# } }}'
            , '<div>'
            , '{{# layui.each(data.quotas, function(index, item){  }}'
            , '<button layim-event="sendPayAmountMessage"  BindAmountInput="AmountInput" receiptAddressId="{{ data.receiptAddressId }}" payType="{{ data.payType }}" amount="{{ item }}" class="layui-btn layui-btn-primary layui-btn-sm justchat-button-custom-amount">{{ item/100 }}</button>'
            , '{{# }) }}'
            , '{{# if(data.amountAllowCustom) {  }}'
            , '<button class="layui-btn layui-btn-primary layui-btn-sm justchat-button-custom-amount" layim-event="sendLayuiHide" style="font-size:12px;" BindAmountInput="AmountInput">手动输入</button>'
            ,'<div class="layui-hide AmountInput ">'
            , '<input type="number" name="title" pattern="\d*" class="layui-input justchat-input-custom-amount " receiptAddressId="{{ data.receiptAddressId }}" payType="{{ data.payType }}"/>'
            ,'<button class="layim-send justchat-send-custom-amount" layim-event="manualSendPayAmountMessage" BindAmountInput="AmountInput">发送</button>'
            ,'</div>'
            , '{{# } }}'
            , '</div>'
            , '</div>'
            , '</li>'].join('');

        var elemChatCustomPayDetail = ['<li class="layim-chat-li{{ d.mine ? " layim-chat-mine" : " layim-chat-target" }}">'
            , '<div class="layim-chat-user" data-userid="{{ d.fromid }}" '
            , isAgency?'layim-event="{{ d.mine ? "" : "openUserInfo" }}">':'>'
            , '<img class="avatar" >'
            , '</div>'
            , '{{# var info = d.content; var json_info = JSON.parse(info);var type = json_info.type;var data = json_info.data; }}'
            , '<div layim-event="goToPay" payUrl="{{ data.payUrl+"&timestamp="+d.timestamp }}" class="justchat-custom-paydetail {{ d.PAY_TYPE_CLASS_NAME[data.payType] }}">'
            , '<div>'
            , '<div class="justchat-custom-paydetial-img"></div>'
            , '<div style="float: left;margin-top: 15px;margin-left: 15px;" class="goToPayText">'
            , '<p style="font-size: 18px;text-align:left:">{{ d.PAY_TYPE_NAME[data.payType] }}'
            , '</p>'
            , '<p style="text-align:left;">点击开始充值'
            , '</p>'
            , '</div>'
            , '</div>'
            , '<div class="justchat-custom-paydetail-btText">收款'
            , '</div>'
            , '</div>'
            , '</li>'].join('');

        //渲染本地最新聊天记录到相应面板
        var viewChatlog = function () {
            var imid = getParam('imid');
            var target_id = getParam('target_id');

            // 设置当前正在聊天对象id
            if(!currentTarget){
                currentTarget = target_id;
            }

            // 一对多
            if(!target_id){
                refreshUserInfo(currentTarget);
            }


            var local = storage.getMyLayimMobile();
            var thatChat = thisChat(), chatlog = local.chatlog || {};
            var ul = thatChat.elem.find('.layim-chat-main ul');

            thatChat.textarea.on('blur',function(){
                setTimeout(function(){
                    document.body.scrollTop = 0;
                    document.documentElement.scrollTop = 0;
                    window.scrollTo(0, 0)
                },100)
            })


            layui.each(chatlog[thatChat.data.type + thatChat.data.id], function (index, item) {
                //justchat 渲染消息
                if (new Date().getTime() > item.timestamp && item.timestamp - (sendMessage.time || 0) > 60 * 1000 * 5) {
                    ul.append('<li class="layim-chat-system"><span>' + getMessageDate(layui.data.date(item.timestamp)) + '</span></li>');
                    sendMessage.time = item.timestamp;
                }
                if(item.mine){
                    item = $.extend(item, {username: cache.mine.username,avatar:cache.mine.avatar})
                }
                if (item.msgType == "IMAGE"){
                    ul.append(laytpl(elemChatPicMain).render(item));
                }else if (item.msgType == "CUSTOM" && item.mine == isAgency) {
                    var info = item.content;
                    var json_info = JSON.parse(info);
                    var type = json_info.type;
                    var data = json_info.data;
                    if (type == "pay:get_pay_type_amount_levels") {
                        ul.append(laytpl(elemChatCustomAmountLevel).render(item));
                    } else if (type == "pay:get_pay_type_detail") {
                        item.PAY_TYPE_NAME = PAY_TYPE_NAME;
                        item.PAY_TYPE_CLASS_NAME = PAY_TYPE_CLASS_NAME;
                        ul.append(laytpl(elemChatCustomPayDetail).render(item));
                    } else if (type == "get_pay_order_detail") {
                        item.PAY_TYPE_NAME = PAY_TYPE_NAME;
                        item.PAY_TYPE_CLASS_NAME = PAY_TYPE_CLASS_NAME;
                        ul.append(laytpl(elemChatCustomPayDetail).render(item));
                    } else {
                    }
                } else {
                    if(item.msgType == "CUSTOM" && item.content && item.content.includes('{')){
                        var json_info = JSON.parse(item.content);
                        var type = json_info.type;
                        var selectpay = json_info.data;
                        if(type== "pay:select_pay_type"){
                            item.content = PAY_TYPE_NAME[selectpay.payType]
                            ul.append(laytpl(elemChatMain).render(item));
                        } else if(type== "pay:select_pay_amount"){
                            item.content = (selectpay.amount/100).toString()
                            ul.append(laytpl(elemChatMain).render(item));
                        }
                    } else {
                       // 官网运营
                        if(item.fromid == officialID){
                            ul.append($(`<li class="official-info-item">${item.content}</li>`))
                            $('.layim-chat form').hide();
                            $('#go-complaint').hide();
                        }
                        else{
                            // 普通消息
                            ul.append(laytpl(elemChatMain).render(item));
                        }

                    }
                }
            });

            initResend(ul);

            setUserInfo(getParam('imid'),function(info){
                $(".layim-chat-mine .layim-chat-user .avatar").attr('src',info.portraitUri);
            })
            setUserInfo(currentTarget,function(info){
                $(".layim-chat-target .avatar").attr('src',info.portraitUri);
            })
            // 清空聊天记录
            clearUnMsgNum(currentTarget);

            chatListMore();

            if(!isAgency) initGoComplaint()

            initAgentQuickReply();
            initSendAccount();
            initPicClick();
        };

        function initPicClick(){
            $('.layim-chat-main ul').on('click','.layui-layim-photos',function(event){
                if(!isAgency) return
                var src = this.src;
                window.open(src,'_blank');
                event.stopPropagation();
                return false;
            })
        }

        // 刷新用户信息
        function refreshUserInfo(target_id){
            if(!target_id) return
            var onSucceedCallback = function (result) {
                if (result.status == 0) {
                    var data = result.data
                    if (!(data.portraitUri)) {
                        data.portraitUri = ''
                    }
                    var friendsInfo = JSON.parse(localStorage.getItem("friendsInfo")) || {};
                    friendsInfo[target_id] = data
                    localStorage.setItem('friendsInfo', JSON.stringify(friendsInfo))
                }
            };
            var onErrorCallback = function () {
                // layer.msg('客服连接异常')
            };
            justchatApiMgr.getUserInfo(target_id, onSucceedCallback, onErrorCallback);
        }

        // 到投诉页面
        function initGoComplaint(){
            var complaint = layui.data('complaint_time');
            var mycomplaint = complaint[getParam('imid')] || {}
            var complaint_time = mycomplaint[currentTarget];

            // 当天不能继续投诉
            if((!complaint_time) || (complaint_time && (complaint_time != (layui.data.date().split(' ')[0])))){
                $('#go-complaint').on('click',function(){
                    if($(this).hasClass('layui-disabled')) return
                    $('#otherPage').trigger('complaintInit').show();
                })
                // 清楚缓存，节约内存
                if(complaint_time){
                    delete mycomplaint[currentTarget]
                    localStorage.setItem('complaint_time',JSON.stringify(complaint))
                }
            }else{
                $('#go-complaint').hide();
            }
        }

        // 清空与某人的未读消息数量，并向控制台发送。
        function clearUnMsgNum(target_id){
             // 将当前好友的对话未读消息数量设置为0
            storage.updateHistoryById({
                id:target_id,
                key:'unMsgNum',
                value:0
            })

             // 重新计算未读消息总数
             var newHistory = storage.getAllHistory();
             var unMsgtotal = 0
             for(var key in newHistory){
                 var item = newHistory[key];
                 if(item.unMsgNum){
                     unMsgtotal += item.unMsgNum;
                 }
             }


             window.parent.postMessage({unMsgtotal:unMsgtotal},"*");
        }

        // 重新发送消息
        function initResend(ul){
            ul.on('click',function (e) {
                var target = e.target;
                if($(target).hasClass('layim-chat-tips')){
                    var index = layer.open({
                        title:'',
                        content: `<div id="isResendLayer" style="background:#fff;padding:28px 40px;margin:0 auto;margin-top: 240px;width:220px;">
                            <p style="margin-bottom:30px;font-size:18px;text-align:center">是否重新发送该消息？</p>
                            <div>
                                <button  style="margin-left:0px;height:30px;line-height:30px;padding: 5px 30px;" class="cancel-btn layui-btn layui-btn-primary">取消</button>
                                <button style="height:30px;line-height:30px;margin-left:20px;padding: 5px 30px;" class="confirm-btn layui-btn">确定</button>
                            </div>
                        </div>`,
                        type:1
                    });

                    var $cancelBtn = $("#isResendLayer .cancel-btn");
                    var $confimBtn = $("#isResendLayer .confirm-btn");
                    $cancelBtn.on('click',function(){
                        layer.close(index);
                        $cancelBtn.off('click');
                        $confimBtn.off('click');
                    })
                    $confimBtn.on('click',function(){
                        var hisChat;

                        var $li = $(target).closest('li');

                        // 清除失败的消息
                        var cid = $li.attr('id').slice(5);

                        var local = layui.data('layim-mobile')[imid];

                        var chatlog = local.chatlog;
                        var chats = chatlog['friend'+currentTarget];

                        for(var i=0;i<chats.length;i++){
                            var chatItem = chats[i];
                            if(chatItem.cid == cid){
                                hisChat = chats.splice(i,1)[0];
                                break;
                            }
                        }

                        layui.data('layim-mobile', {
                            key: imid
                            , value: local
                        });



                        // 支付类型消息
                        if($li.hasClass('layim-chat-pay')){
                            var paytype = $li.data("paytype");
                            sendPayTypeMessage(paytype);
                        }
                        else if($li.hasClass('layim-chat-amount')){
                            // 支付数量消息
                            var payType = $li.data("paytype");
                            var receiptAddressId = $li.data("receiptaddressid");
                            var payAmount = $li.data("payamount");
                            sendPayAmountMessage(payAmount,receiptAddressId,payType);

                        }
                        else if($li.hasClass('layim-chat-img')){
                            console.log(hisChat.content)
                            sendPicToChat(hisChat.content,uuid())
                        }
                        else{
                            // 普通消息重发
                            var text = $(target).siblings(".layim-chat-text").text();
                            sendMessage(hisChat.content);
                        }

                        $li.remove();

                        layer.close(index);

                        $cancelBtn.off('click');
                        $confimBtn.off('click');
                    })
                }
            })
        }

        //查看更多记录
        var chatListMore = function () {
            var thatChat = thisChat(), chatMain = thatChat.elem.find('.layim-chat-main');
            var ul = chatMain.find('ul'), li = ul.children('.layim-chat-li');

            if (li.length > MAX_ITEM) {
                var first = li.eq(0);
                first.prev().remove();
                if (!ul.prev().hasClass('layim-chat-system')) {
                    // ul.before('<div class="layim-chat-system"><span layim-event="chatLog">查看更多记录</span></div>');
                    ul.before('<div class="layim-chat-system"><span style="color:#E53333">只能查看最近100条消息</span></div>');
                }
                first.remove();
            }
            chatMain.scrollTop(chatMain[0].scrollHeight + 1000);
        };

        //快捷键发送
        var hotkeySend = function () {
            var thatChat = thisChat(), textarea = thatChat.textarea;
            // var btn = textarea.next();
            var btn = textarea.siblings('.layim-send');
            textarea.off('keyup').on('keyup', function (e) {
                $(".AmountInput").addClass("layui-hide")
                var keyCode = e.keyCode;
                if (keyCode === 13) {
                    e.preventDefault();
                    sendMessage();
                }
                // btn[textarea.val() === '' ? 'addClass' : 'removeClass']('layui-disabled');

            });

            textarea.off('input').on('input', function (e) {
                $(".AmountInput").addClass("layui-hide");
                toggelSendBtn();
            });

        };

        //表情库
        var faces = function () {
            var alt = ["[微笑]", "[嘻嘻]", "[哈哈]", "[可爱]", "[可怜]", "[挖鼻]", "[吃惊]", "[害羞]", "[挤眼]", "[闭嘴]", "[鄙视]", "[爱你]", "[泪]", "[偷笑]", "[亲亲]", "[生病]", "[太开心]", "[白眼]", "[右哼哼]", "[左哼哼]", "[嘘]", "[衰]", "[委屈]", "[吐]", "[哈欠]", "[抱抱]", "[怒]", "[疑问]", "[馋嘴]", "[拜拜]", "[思考]", "[汗]", "[困]", "[睡]", "[钱]", "[失望]", "[酷]", "[色]", "[哼]", "[鼓掌]", "[晕]", "[悲伤]", "[抓狂]", "[黑线]", "[阴险]", "[怒骂]", "[互粉]", "[心]", "[伤心]", "[猪头]", "[熊猫]", "[兔子]", "[ok]", "[耶]", "[good]", "[NO]", "[赞]", "[来]", "[弱]", "[草泥马]", "[神马]", "[囧]", "[浮云]", "[给力]", "[围观]", "[威武]", "[奥特曼]", "[礼物]", "[钟]", "[话筒]", "[蜡烛]", "[蛋糕]"],
                arr = {};
            layui.each(alt, function (index, item) {
                arr[item] = layui.cache.dir + 'images/face/' + index + '.gif';
            });
            return arr;
        }();
        //聊天面板都返回事件-关闭浏览器页面(游戏端提供方法)
        var  closeBrowserPage=function () {
            justchatSocketMgr.close()
            if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.ibc) {
                console.log("===");
                window.webkit.messageHandlers.ibc.postMessage({'action': 'quit'},"*");
            } else if (window.abc) {
                window.abc.quitBrowser();
            } else {
            }
        }
        var stope = layui.stope; //组件事件冒泡

        //在焦点处插入内容
        var focusInsert = function (obj, str, nofocus) {
            var result, val = obj.value;
            // nofocus || setTimeout(function(){
            //     obj.focus();
            // },300)
            if (document.selection) { //ie
                result = document.selection.createRange();
                document.selection.empty();
                result.text = str;
            } else {
                // result = [val.substring(0, obj.selectionStart), str, val.substr(obj.selectionEnd)];
                // nofocus || obj.focus();
                obj.value = [val,str].join('');
            }
        };
        //动态显示和添加
        var sendLayuiTogHide=function (othis,IsHide) {
            var BindAmountInput = othis.attr("BindAmountInput");
            $("."+BindAmountInput).removeClass("layui-hide").addClass("layui-hide")
            var bindDiv=othis.parents(".layim-chat-text").find("."+BindAmountInput);
            if(IsHide){
                bindDiv.removeClass("layui-hide");
                var textarea =bindDiv.find("input");
                // var btn = textarea.next();
                var btn = textarea.siblings('.layim-send');
                textarea.off('input').on('input', function (e) {
                    // btn[textarea.val() === '' ? 'addClass' : 'removeClass']('layui-disabled');
                    toggelSendBtn();
                });
            }

        }

        //  sessionStorage管理
        function session(obj) {
            var type = obj.type;
            var value = obj.value;
            var key = obj.key;
            switch(type){
                case 'set':
                    sessionStorage.setItem(key,value);
                    break;
                case 'get':
                    return sessionStorage.getItem(key);
                case 'delete':
                    sessionStorage.removeItem(key);
                    break;
            }
        }

        function getParam(paramName) {
            var paramValue = "", isFound = !1;
            if (window.location.search.indexOf("?") == 0 && window.location.search.indexOf("=") > 1) {
                var arrSource = unescape(window.location.search).substring(1, window.location.search.length).split("&"), i = 0;
                while (i < arrSource.length && !isFound) arrSource[i].indexOf("=") > 0 && arrSource[i].split("=")[0].toLowerCase() == paramName.toLowerCase() && (paramValue = arrSource[i].split("=")[1], isFound = !0), i++
            }
            return paramValue == "" && (paramValue = null), paramValue
        };

        window.addEventListener("message", function(e){
          if(e.data.type =="imBackParent")
          $(".layim-title .layim-chat-back").trigger("touch")
          $(".layim-title .layim-chat-back").trigger("click")
          // events.back()
        });
        //事件
        var events = {
            //弹出聊天面板
            chat: function (othis,e) {
                // 点击删除聊天，忽略
                if($(e.target).hasClass('delete-layim-chat-li')) return


                var local = storage.getMyLayimMobile();
                var type = othis.data('type'), index = othis.data('index');
                var list = othis.attr('data-list') || othis.index(), data = {};
                if (type === 'friend') {
                    data = cache[type][index].list[list];
                } else if (type === 'group') {
                    data = cache[type][list];
                } else if (type === 'history') {
                    data = (local.history || {})[index] || {};
                }
                data.name = data.name || data.username || data.groupname;
                if (type !== 'history') {
                    data.type = type;
                }

                // 设置当前的聊天对象id
                currentTarget = index.slice(6)

                session({
                    type:'set',
                    key:'target',
                    value:JSON.stringify(data)
                })

                popchat(data, true);

                setUserInfo(getParam('imid'),function(info){
                    $(".layim-chat-mine .layim-chat-user .avatar").attr('src',info.portraitUri);
                })
                setUserInfo(index.slice(6),function(info){
                    $(".layim-chat-target .avatar").attr('src',info.portraitUri);
                    $(".chat-title").text(info.nickname);
                })

                $('.layim-' + data.type + data.id).find('.layim-msg-status').removeClass(SHOW);

                layui.each(call.chat, function (index, item) {
                    setTimeout(function () {
                        item && item(othis.data('index'));
                    }, 200);
                });
            }

            //展开联系人分组
            , spread: function (othis) {
                var type = othis.attr('lay-type');
                var spread = type === 'true' ? 'false' : 'true';
                var local = layui.data('layim-mobile')[cache.mine.id] || {};
                othis.next()[type === 'true' ? 'removeClass' : 'addClass'](SHOW);
                local['spread' + othis.parent().index()] = spread;
                layui.data('layim-mobile', {
                    key: cache.mine.id
                    , value: local
                });
                othis.attr('lay-type', spread);
                othis.find('.layui-icon').html(spread === 'true' ? '&#xe61a;' : '&#xe602;');
            }

            //底部导航切换
            , tab: function (othis) {
                var index = othis.index(), main = '.layim-tab-content';
                othis.addClass(THIS).siblings().removeClass(THIS);
                layimMain.find(main).eq(index).addClass(SHOW).siblings(main).removeClass(SHOW);
            }

            //返回到上一个面板
            , back: function (othis) {
                var layero = othis.parents('.layui-m-layer').eq(0)
                    , index = layero.attr('index')
                    , PANEL = '.layim-panel';
                setTimeout(function () {
                    layer.close(index);
                }, 300);
                //一对一
                if(!(location.search.includes("chatType=0"))){
                    if(isAgency){
                        window.parent.postMessage({"closeIm": true},"*");
                    } else {
                        //关闭游戏客户端
                        closeBrowserPage();
                    }
                    return;
                }
                session({
                    type:'delete',
                    key:'target'
                })
                currentTarget = null;
                othis.parents(PANEL).eq(0).removeClass('layui-m-anim-left').addClass('layui-m-anim-rout');
                layero.prev().find(PANEL).eq(0).removeClass('layui-m-anim-lout').addClass('layui-m-anim-right');
                layui.each(call.back, function (index, item) {
                    setTimeout(function () {
                        item && item();
                    }, 200);
                });

                resetListInfo();
                initDeleteHistoryItem();

                // 重置未读消息数量
                if (!layimMain) return;
                var unRreadNum = 0;

                var localHistory = storage.getAllHistory();
                for(var key in localHistory){
                    var item = localHistory[key];
                    if(item.unMsgNum){
                        unRreadNum += item.unMsgNum
                    }
                }

                initUI_justchat(unRreadNum);
            }

            , closeIm: function () {
                if(isAgency){
                    window.parent.postMessage({"closeIm": true},"*");
                } else {
                    //关闭游戏客户端
                    closeBrowserPage();
                }
            }

            //发送聊天内容
            ,send: function(othis){
                console.warn(othis)
                var SendMessage = othis.attr("SendMessage");
                sendMessage(SendMessage);
            }
            , manualSendPayAmountMessage:function(othis){
                if(isAgency){
                    layer.msg("代理不可操作此功能")
                    return
                }
                var BindAmountInput = othis.attr("BindAmountInput");
                var bindInput=othis.parent("."+BindAmountInput).find("input");
                var val= bindInput.val();

                if(val<50 || val> 50000){
                    layer.msg('自定义金额范围为50-50000');
                    return
                }else if(!Number.isInteger(parseFloat(val))){
                    layer.msg('自定义金额只能为整数')
                    return
                }
                bindInput.val("");
                var amount = val*100;
                var receiptAddressId = bindInput.attr("receiptAddressId"),payType = bindInput.attr("payType");
                sendPayAmountMessage(amount, receiptAddressId, payType);
                // othis.addClass('layui-disabled');

            }

            //justchat
            , sendPayTypeMessage: function (othis, e) {
                var paytype = othis.attr("paytype");
                sendPayTypeMessage(paytype);
            }

            , openUserInfo: function (othis, e) {
                var uesrid=othis.attr("data-userid")
                // var token = getParam("token");
                // window.location.href = `./../user/userInfo.html?token=${token}&target_id=${uesrid}`
                $('#otherPage').trigger('userpageInit',uesrid).show();
            }

            , goToPay: function (othis, e) {
                var payurl = othis.attr("payurl");
                location.href=payurl +'&v=1.2.2'
            }

            , sendPayAmountMessage: function (othis, e) {
                if(isAgency){
                    layer.msg("代理不可操作此功能")
                    return
                }
                var amount = othis.attr("amount");
                var receiptAddressId = othis.attr("receiptAddressId"),payType = othis.attr("payType");
                sendPayAmountMessage(amount, receiptAddressId, payType);
                sendLayuiTogHide(othis);
            }
            , sendLayuiHide:function (othis) {
                sendLayuiTogHide(othis,true);
            }

            // 清除历史消息
            , clearStorage:function () {
                popConfirm({
                    content:'清空所有历史数据？',
                    ok:function(){
                        window.localStorage.removeItem('friendsInfo')
                        window.localStorage.removeItem('layim-mobile')
                        window.localStorage.removeItem('maxInfo')
                        if(isAgency){
                            window.parent.postMessage({unMsgtotal:0},"*");
                        }
                        $(".layim-list-history").html('<li class="layim-null">暂无任何消息</li>');
                        $("#layui-m-layer0 .layim-chat-status").html('<span class="chat-title">消息</span><span class="justchat-status"></span>');
                    }
                })
            }

            //表情
            , face: function (othis, e) {
                var content = '', thatChat = thisChat(),
                    input = thatChat.textarea, chatMain = thatChat.elem.find('.layim-chat-main');
                layui.each(faces, function (key, item) {
                    content += '<li title="' + key + '" layim-event="selectFace"><img src="' + item + '"></li>';
                });
                content = '<ul class="layui-layim-face layerim-face">' + content + '</ul>';

                $(".layim-chat-footer .layim-chat-tool").addClass('layui-hide')
                if($(".layim-chat-footer .layerim-face").hasClass('layui-layim-face')){
                    $(".layim-chat-footer .layui-layim-face").remove()
                    $('.layim-chat-footer .layim-tool-face').html('&#xe60c;')
                    input[0].focus()
                } else {
                    input[0].blur()
                    $('.layim-chat-footer .layim-tool-face').html('<span class="icon iconfont">&#xe624;</span>')
                    $(".layim-chat-footer").append(content)
                    setTimeout(function () {
                        chatMain.scrollTop(chatMain[0].scrollHeight + 1000);
                    }, 500);
                }
                // var facelist = $(".layim-chat-footer .layerim-face").children('li')
                // facelist.off('click', events.faceHide).on('click', function (){
                // })
                // layer.popBottom({
                //     content: content
                //     , success: function (elem) {
                //         var list = $(elem).find('.layui-layim-face').children('li')
                //         touch(list, function () {
                //             focusInsert(input[0], 'face' + this.title + ' ', false);
                //             // input.next()[input.val() === '' ? 'addClass' : 'removeClass']('layui-disabled');
                //             toggelSendBtn();
                //             return false;
                //         });
                //     }
                // });

                var doc = $(".layim-chat-main");
                if (isTouch) {
                    doc.off('touchend', events.faceHide).on('touchend', events.faceHide);
                } else {
                    doc.off('click', events.faceHide).on('click', events.faceHide);
                }
                stope(e);
            }, faceHide: function () {
                // layer.close(layer.popBottom.index);
                // $(document).off('touchend', events.faceHide)
                //     .off('click', events.faceHide);

                if($(".layim-chat-footer .layerim-face").hasClass('layui-layim-face')){
                    $(".layim-chat-footer .layui-layim-face").remove()
                    $('.layim-chat-footer .layim-tool-face').html('&#xe60c;')
                }
            }, selectFace: function () {
                var thatChat = thisChat(), input = thatChat.textarea;
                focusInsert(input[0], 'face' + this.title + ' ', false);
                // input.next()[input.val() === '' ? 'addClass' : 'removeClass']('layui-disabled');
                toggelSendBtn();
                return false;
            }

            //图片或一般文件
            , image: function (othis) {
                var type = othis.data('type') || 'images', api = {
                    images: 'uploadImage'
                    , file: 'uploadFile'
                }
                    , thatChat = thisChat(), conf = cache.base[api[type]] || {};

                upload({
                    url: conf.url || ''
                    , method: conf.type
                    , elem: othis.find('input')[0]
                    , unwrap: true
                    , type: type
                    , success: function (res) {
                        if (res.code == 0) {
                            res.data = res.data || {};
                            if (type === 'images') {
                                focusInsert(thatChat.textarea[0], 'img[' + (res.data.src || '') + ']');
                            } else if (type === 'file') {
                                focusInsert(thatChat.textarea[0], 'file(' + (res.data.src || '') + ')[' + (res.data.name || '下载文件') + ']');
                            }
                            sendMessage();
                        } else {
                            layer.msg(res.msg || '上传失败');
                        }
                    }
                });
            }

            //扩展工具栏
            , extend: function (othis) {
                var filter = othis.attr('lay-filter')
                    , thatChat = thisChat();

                layui.each(call['tool(' + filter + ')'], function (index, item) {
                    item && item.call(othis, function (content) {
                        focusInsert(thatChat.textarea[0], content);
                    }, sendMessage, thatChat);
                });
            }

            //弹出新的朋友面板
            , newFriend: function () {
                layui.each(call.newFriend, function (index, item) {
                    item && item();
                });
            }

            //弹出群组面板
            , group: function () {
                popPanel({
                    title: '群聊'
                    , tpl: ['<div class="layui-layim-list layim-list-group">'
                        , listTpl({
                            type: 'group'
                            , item: 'd.group'
                        })
                        , '</div>'].join('')
                    , data: {}
                });
            }

            //查看群组成员
            , detail: function () {
                var thatChat = thisChat();
                layui.each(call.detail, function (index, item) {
                    item && item(thatChat.data);
                });
            }

            //播放音频
            , playAudio: function (othis) {
                var audioData = othis.data('audio')
                    , audio = audioData || document.createElement('audio')
                    , pause = function () {
                    audio.pause();
                    othis.removeAttr('status');
                    othis.find('i').html('&#xe652;');
                };
                if (othis.data('error')) {
                    return layer.msg('播放音频源异常');
                }
                if (!audio.play) {
                    return layer.msg('您的浏览器不支持audio');
                }
                if (othis.attr('status')) {
                    pause();
                } else {
                    audioData || (audio.src = othis.data('src'));
                    audio.play();
                    othis.attr('status', 'pause');
                    othis.data('audio', audio);
                    othis.find('i').html('&#xe651;');
                    //播放结束
                    audio.onended = function () {
                        pause();
                    };
                    //播放异常
                    audio.onerror = function () {
                        layer.msg('播放音频源异常');
                        othis.data('error', true);
                        pause();
                    };
                }
            }

            //播放视频
            , playVideo: function (othis) {
                var videoData = othis.data('src')
                    , video = document.createElement('video');
                if (!video.play) {
                    return layer.msg('您的浏览器不支持video');
                }
                layer.close(events.playVideo.index);
                events.playVideo.index = layer.open({
                    type: 1
                    ,
                    anim: false
                    ,
                    style: 'width: 100%; height: 50%;'
                    ,
                    content: '<div style="background-color: #000; height: 100%;"><video style="position: absolute; width: 100%; height: 100%;" src="' + videoData + '" autoplay="autoplay"></video></div>'
                });
            }

            //聊天记录
            // , chatLog: function (othis) {
            //     var thatChat = thisChat();
            //     layui.each(call.chatlog, function (index, item) {
            //         item && item(thatChat.data, thatChat.elem.find('.layim-chat-main>ul'));
            //     });
            // }

            //更多列表
            , moreList: function (othis) {
                var filter = othis.attr('lay-filter');
                layui.each(call.moreList, function (index, item) {
                    item && item({
                        alias: filter
                    });
                });
            }

            //关于
            , about: function () {
                layer.open({
                    content: '<p style="padding-bottom: 5px;">LayIM属于付费产品，欢迎通过官网获得授权，促进良性发展！</p><p>当前版本：layim mobile v' + v + '</p><p>版权所有：<a href="http://layim.layui.com" target="_blank">layim.layui.com</a></p>'
                    , className: 'layim-about'
                    , shadeClose: false
                    , btn: '我知道了'
                });
            }
                    // 展开聊天工具栏
           ,toggleTools:(function() {
                var tag = false;
                return function(){
                    var $tools = $('.layim-chat-tool');
                    var $main = $('.layim-chat-main');
                    var main = $main.get(0);

                    // 展开工具栏
                    if($tools.hasClass('layui-hide')){
                        open()
                        if($(".layim-chat-footer .layerim-face").hasClass('layui-layim-face')){
                            $(".layim-chat-footer .layui-layim-face").remove()
                            $('.layim-chat-footer .layim-tool-face').html('&#xe60c;')
                        }
                    } // 收缩工具栏
                    else{
                        close()
                    }
                    function open(){
                        $tools.removeClass('layui-hide');
                        main.scrollTop = main.scrollHeight;
                    }


                    function close(){
                        $tools.addClass('layui-hide');
                        main.scrollTop = main.scrollHeight;
                        return false;
                    }

                    if(!tag){
                        $('.layim-chat-main').on('click',function(){
                            $tools.addClass('layui-hide');
                            return false
                        })
                        var arr = [$('.layim-chat-send input'),$('.layim-tool-face')]
                        arr.forEach(function ($item) {
                            $item.on('click',close);
                        })
                        tag = true;
                    }

                }
            })()

        };

        //暴露接口
        exports('layim-mobile', new LAYIM());

    })
})
